package m.jclecai.com.activity;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import m.jclecai.com.R;

import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.adapter.ExpandJCLQAdapter;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.NotifyTextViewSetChanged;
import m.jclecai.com.pop.MyGuideMenuPopUpWindow;
import m.jclecai.com.pop.MyLotteryMenuPopUpWindow;
import m.jclecai.com.ui.ZQ_LQ_LotteryDetailsActivity;
import m.jclecai.com.utils.DataUtil;
import m.jclecai.com.utils.MyLog;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.AutoSwipeRefreshLayout;
import m.jclecai.com.view.CustomExpandListview;

import static m.jclecai.com.utils.Utils.ZQ_ITEM_LIST;
import static m.jclecai.com.utils.Utils.jclqGroup;
import static m.jclecai.com.utils.Utils.zq_jczqChilds;

public class LotteryJCLQActivity extends BaseActivity implements
        NotifyTextViewSetChanged, SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.rl_bar)
    RelativeLayout rl_bar;
    @BindView(R.id.expand_list)
    CustomExpandListview expand_list;
    @BindView(R.id.toolbar_delete)
    TextView toolbar_delete;
    @BindView(R.id.toolbar_hiti)
    TextView toolbar_hiti;
    @BindView(R.id.toolbar_confirm)
    TextView toolbar_confirm;
    @BindView(R.id.sr_refresh)
    AutoSwipeRefreshLayout refreshLayout;
    private Integer pager = 3;
    ExpandJCLQAdapter adapter;
    String[] names;
    MyLotteryMenuPopUpWindow popUpWindow;
    MyGuideMenuPopUpWindow guideWindow;

    TreeMap<String, List<String[]>> jczqData;

    @Override
    public int getContentView() {
        return R.layout.activity_jczq;
    }


    @Override
    public void initView() {
        rightOptionText("", R.drawable.action_menu);
        setTitle("混合投注", R.drawable.gs);
        leftOptionText("");
        refreshLayout.setOnRefreshListener(this);
        //总进球
        adapter = new ExpandJCLQAdapter(this, pager, this, expand_list);

        adapter.setPager(3);
        //悬浮的标题
        expand_list.setHeaderView(getLayoutInflater().inflate(
                R.layout.item_parent, expand_list, false));
        expand_list.setAdapter(adapter);
        initLoadingLayout(refreshLayout);
        showExceptButton(false);
        refreshLayout.setRefreshing(true);
    }

    @Override
    public void initData() {
        initPopupView();
        iniPopupWindow();
        getList();
    }

    void getList() {
        HttpManager.getAsyn(Constant_Url.JCLQ_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                dissDialog();
                if (refreshLayout != null)
                    refreshLayout.setRefreshing(false);
                showInternetOffLayout();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                ZQ_ITEM_LIST.clear();
                closeLoadingLayout();
                if (refreshLayout != null)
                    refreshLayout.setRefreshing(false);
                if (!TextUtils.isEmpty(response)) {
                    jczqData = DataUtil.getJCLQData(response, DataUtil.LotteryType.JCLQ);
                    if (pager == 5) {
                        DataUtil.getJCLQMatchInfoDG(jczqData);//竞彩篮球单关
                    } else {
                        DataUtil.getJCLQMatchInfo2(jczqData);//胜平负
                    }
                    adapter.notifyDataSetChanged();
                    for (int i = 0; i < adapter.getGroupCount(); i++) {// 默认全部展开
                        expand_list.expandGroup(i);
                    }
                }
                if (zq_jczqChilds.size() <= 0)
                    showEmptyLayout("暂无比赛~",R.mipmap.img_blank_match);
            }
        });
    }

    //返回
    @OnClick(R.id.tv_back)
    void back() {
        onBackPressed();
    }

    //清空选中信息
    @OnClick(R.id.toolbar_delete)
    void clearInfo() {
        toolbar_hiti.setText("请选择比赛");
        ZQ_ITEM_LIST.clear();
        adapter.resetStatus();
    }

    //显示主菜单
    @OnClick({R.id.tv_mid_title, R.id.iv_title_icon})
    void showMainMenu() {
        startAnimation(ivTitleIcon, R.anim.rotate_0_180);
        popUpWindow.setPager(pager);
        popUpWindow.showAsDropDown(rl_bar);
    }

    //显示帮助菜单
    @OnClick(R.id.tv_right_option)
    void showHelp() {
        guideWindow.showAsDropDown(tvMidTitle, guideWindow.getWidth(), guideWindow.getHeight());
    }

    @Override
    protected void onResume() {
        super.onResume();
        adapter.resetStatus();
        onClickSetChangedText();
    }

    //跳转到投注界面
    @OnClick(R.id.toolbar_confirm)
    void confirm() {
        if (isDG() && ZQ_ITEM_LIST.size() < 1
                || (!isDG()) && ZQ_ITEM_LIST.size() < 2) {
            MyToast.showToast(this, "至少选择2场比赛");
            return;
        }
        if (ZQ_ITEM_LIST.size() > 8) {
            MyToast.showToast(this, "单次投注最多8场比赛");
            return;
        }
        Intent intent = new Intent(this,
                BettingJCLQActivity.class);
        intent.putExtra("name", names[pager]);
        intent.putExtra("pager", pager);
        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
    }

    @Override
    public void onClickSetChangedText() {
        toolbar_hiti.setText("");
        if (ZQ_ITEM_LIST.size() == 0) {
            toolbar_hiti.setText("请选择比赛");
        } else if (ZQ_ITEM_LIST.size() == 1) {
            toolbar_hiti.setText(isDG() ? "已选1场" : "已选1场，还差1场");
        } else if (ZQ_ITEM_LIST.size() > 8) {
            MyToast.showToast(this, "单次投注最多8场比赛");
            ZQ_ITEM_LIST.remove(ZQ_ITEM_LIST.size() - 1);
            adapter.resetStatus();
            onClickSetChangedText();
        } else {
            toolbar_hiti.setText("已选" + ZQ_ITEM_LIST.size() + "场");
        }
    }

    @Override
    public void onBackPressed() {
        if (ZQ_ITEM_LIST.size() > 0)
            showAlertDialog("提示", "返回大厅将清空所有数据?", "取消", "确认", null,
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            clearAllData();
                        }
                    });
        else
            clearAllData();
    }

    @Override
    public void onDestroy() {
        clearAllData();
        super.onDestroy();
    }

    /**
     * @category 标题右侧菜单
     */
    private void initPopupView() {
        guideWindow = new MyGuideMenuPopUpWindow(this);
        guideWindow.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.tv_kaijiang:
                        Intent intentKaiJiang = new Intent(LotteryJCLQActivity.this, ZQ_LQ_LotteryDetailsActivity.class);
                        intentKaiJiang.putExtra("type", "jclq");
                        intentKaiJiang.putExtra("typeName","竞彩蓝球");
                        startActivity(intentKaiJiang);
                        break;
                    case R.id.tv_playing:
                        Intent intent = new Intent(LotteryJCLQActivity.this, WebHelperActivity.class);
                        intent.putExtra("title", "玩法介绍");
                        //intent.putExtra("code", Constant_Url.PLAYING_URL);
                        intent.putExtra("code", "jclq");
                        intent.putExtra("isLocal", true);
                        startActivity(intent);
                        break;
                    case R.id.tv_guide:
                        break;
                }
            }
        });
    }

    //标题主菜单
    private void iniPopupWindow() {
        names = getResources().getStringArray(
                R.array.jclq_types_name_list);
        String[] types = getResources().getStringArray(R.array.jclq_types_list);
        popUpWindow = new MyLotteryMenuPopUpWindow(this, names, types, pager,
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        closeLoadingLayout();
                        ZQ_ITEM_LIST.clear();
                        pager = position;
                        setTitle(names[pager]);
                        popUpWindow.notifyDataSetChanged();
                        onClickSetChangedText();
                        if (popUpWindow.isShowing()) {
                            popUpWindow.dismiss();
                        }

                        if (pager == 5) {
                            DataUtil.getJCLQMatchInfoDG(jczqData);//竞彩篮球单关
                        } else {
                            DataUtil.getJCLQMatchInfo2(jczqData);//胜平负
                        }
                        adapter.setPager(pager);
                        if (zq_jczqChilds.size() <= 0)
                            showEmptyLayout("暂无比赛~",R.mipmap.img_blank_match);
                        for (int i = 0; i < adapter.getGroupCount(); i++) {// 默认全部展开
                            expand_list.collapseGroup(i);
                            expand_list.expandGroup(i);
                        }
                    }
                }, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startAnimation(ivTitleIcon, R.anim.rotate_180_360);
            }
        });
    }

    //支持单关的小蓝点
    boolean isDG() {
        boolean isDG = false;
        for (int i = 0; i < ZQ_ITEM_LIST.size(); i++) {
            String value = ZQ_ITEM_LIST.get(i).getCodes()[18];
            int dValue = TextUtils.isEmpty(value) ? 0 : Integer.parseInt(value);
            StringBuilder sb = new StringBuilder();
            //解析成二进制串 支持单关标志1 不支持标志0
            String s = Integer.toBinaryString(dValue);
            //因为篮球有4个玩法 计算顺序为
            //胜负 让份胜负 胜分差 大小分
            //  0      0       1     1
            //其中总进球 比分 半全场 永远支持单关
            //因为我是直接从左往右拆分二进制
            int num = 4 - s.length();
            //num 是需要补齐位数 默认补齐0 例如7 = 111  补齐为0111
            //所以左->右前两个玩法为0 不支持单关
            for (int j = 0; j < num; j++) {
                //补齐位数 默认补齐0
                sb.append("0");
            }
            sb.append(s);
            //    胜负       让份胜负      大小分       胜分差
            switch (pager) {
                case 0:
                    isDG = "1".equals(String.valueOf(sb.charAt(0)));
                    break;
                case 1:
                    isDG = "1".equals(String.valueOf(sb.charAt(1)));
                    break;
                case 2:
                    isDG = "1".equals(String.valueOf(sb.charAt(3)));
                    break;
                case 4:
                    isDG = "1".equals(String.valueOf(sb.charAt(2)));
                    break;
            }
            if (pager == 5) isDG = true;
            if (isDG) break;
        }
        return isDG;
    }

    /**
     * 清除所有的数据
     */
    public void clearAllData() {
        ZQ_ITEM_LIST.clear();
        zq_jczqChilds.clear();
        jclqGroup.clear();
        finish();
    }

    @Override
    public void onRefresh() {
        getList();
    }

    @Override
    public void OnRetry(String btnMessage) {
        refreshLayout.setRefreshing(true);
        closeLoadingLayout();
        getList();
    }
}
